package com.yfl.realm;


import com.yfl.domain.SysUser;
import com.yfl.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * UserRealm 用户的认证和制授权的实现
 * spring-shiro.xml 创建了UserRealm 该 对象
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取用户的名称
        String username = token.getPrincipal().toString();
        // 使用用户名查询用户
        SysUser user = userService.findUserByUsername(username);
        // 判断用户是否为空
        if (user == null) {
            return null;
        }
        ActiveUser activeUser = new ActiveUser();
        activeUser.setUser(user);
        activeUser.setRoles(null);
        activeUser.setPerms(null);
        // tip:如果我们的数据库没有预留salt这个字段,我们可以使用一个项目的名称 或组织名称代替这个字段
        return new SimpleAuthenticationInfo(user,user.getLoginPassword(), ByteSource.Util.bytes("yfl"),username);
    }

    public static void main(String[] args) {
        Md5Hash hash = new Md5Hash("123456", "yfl", 2);
        System.out.println(hash.toHex());
    }
}
